﻿using System;
using System.Data;
using K9Nano.Dependency;
using K9Nano.Domain;
using Microsoft.Extensions.Options;
using MySql.Data.MySqlClient;

namespace K9Nano.MySql
{
    public class MySqlReadOnlyDbConnectionFactory : IReadOnlyDbConnectionFactory, IScopedDependency, IDisposable
    {
        public IDbConnection ReadOnlyDbConnection { get; private set; }

        public MySqlOption MySqlOption { get; }

        private readonly string _sharedPlaceholder;

        private readonly string _shared;

        public MySqlReadOnlyDbConnectionFactory(IOptionsMonitor<MySqlOption> options)
        {
            MySqlOption = options.CurrentValue;
            ReadOnlyDbConnection = new MySqlConnection(MySqlOption.ConnectionString);

            _sharedPlaceholder = $" {Share.K9SharedConstants.SharedSchemePlaceholder}.";
            _shared = $" {MySqlOption.SharedScheme}.";
        }

        public IDbConnection CreateConnection()
        {
            return new MySqlConnection(MySqlOption.ConnectionString);
        }

        public string PrepareSharedSql(string sql)
        {
            return sql.Replace(_sharedPlaceholder, _shared);
        }

        protected virtual void Dispose(bool disposing)
        {
            if (ReadOnlyDbConnection == null) return;
            if (disposing)
            {
                ReadOnlyDbConnection.Dispose();
                ReadOnlyDbConnection = null;
            }
        }

        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }

        ~MySqlReadOnlyDbConnectionFactory()
        {
            Dispose(false);
        }
    }
}